package jmotioncapture.calculation;

import java.util.Vector;

import jmotioncapture.geometry2D.Point;
import jmotioncapture.geometry2D.Rectangle;
import jmotioncapture.geometry2D.Square;

public class ShapeRecognizer {

	public static boolean isRectangle(Vector<Point> pts) {
		if (pts.size() != 4)
			return false;

		Point pt1 = pts.elementAt(0);
		Point pt2 = pts.elementAt(1);
		Point pt3 = pts.elementAt(2);
		Point pt4 = pts.elementAt(3);

		if (Math.abs(GeomCalculation
				.getAngleBetweenTwoLines(pt1, pt2, pt2, pt3)) - 90 > Rectangle.ANGLE_TOLERANCE)
			return false;

		if (Math.abs(GeomCalculation
				.getAngleBetweenTwoLines(pt2, pt3, pt3, pt4)) - 90 > Rectangle.ANGLE_TOLERANCE)
			return false;

		if (Math.abs(GeomCalculation
				.getAngleBetweenTwoLines(pt3, pt4, pt4, pt1)) - 90 > Rectangle.ANGLE_TOLERANCE)
			return false;

		if (Math.abs(GeomCalculation
				.getAngleBetweenTwoLines(pt4, pt1, pt1, pt2)) - 90 > Rectangle.ANGLE_TOLERANCE)
			return false;

		return true;
	}

	public static boolean isSquare(Vector<Point> pts) {

		if (!isRectangle(pts))
			return false;

		double[] length = new double[4];
		length[0] = Math.abs(GeomCalculation.distance(pts.elementAt(0), pts
				.elementAt(1)));
		length[1] = Math.abs(GeomCalculation.distance(pts.elementAt(1), pts
				.elementAt(2)));
		length[2] = Math.abs(GeomCalculation.distance(pts.elementAt(2), pts
				.elementAt(3)));
		length[3] = Math.abs(GeomCalculation.distance(pts.elementAt(0), pts
				.elementAt(3)));

		// Compare: 01;02;03;12;13;23
		if (Math.abs(length[0] - length[1]) > Square.LENGTH_TOLERANCE)
			return false;
		
		if (Math.abs(length[0] - length[2]) > Square.LENGTH_TOLERANCE)
			return false;
		
		if (Math.abs(length[0] - length[3]) > Square.LENGTH_TOLERANCE)
			return false;
		
		if (Math.abs(length[1] - length[2]) > Square.LENGTH_TOLERANCE)
			return false;
		
		if (Math.abs(length[1] - length[3]) > Square.LENGTH_TOLERANCE)
			return false;
		
		if (Math.abs(length[2] - length[3]) > Square.LENGTH_TOLERANCE)
			return false;
		

		return true;
	}
}
